package com.mingtang.online.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.mingtang.online.R;

import java.util.HashMap;
import java.util.Map;


@SuppressLint("SetJavaScriptEnabled")
public class V6WebviewChildActivity extends BaseActivity {

//js交互详情页面 本页面适用商品支付 详情 完成回调reload即可
    private WebView v4_webview;
    private RelativeLayout rl_back;
    //	private ProgressBar bar;

    Map<String, String> extraHeaders;
    private int reload = 0;
    private String active_url;

    private int active;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v4_webview_activity);
        initView();
        initData();
        v4_webview.loadUrl(active_url, extraHeaders);
    }


    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initData() {
        extraHeaders = new HashMap<String, String>();
        extraHeaders.put("token", "str");
        v4_webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("banner_url", url);


                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub

                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {

            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              String url) {
                // TODO Auto-generated method stub
//		Log.e("header_ss", request.getRequestHeaders().toString());
                WebResourceResponse response = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    response = super.shouldInterceptRequest(view, url);

                }
                return response;
//	return super.shouldInterceptRequest(view, url);
            }

        });
        v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);

        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);

        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");

        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(V6WebviewChildActivity.this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        // This next one is crazy. It's the DEFAULT location for your app's
        // cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();
        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");


    }


    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, arg2);

        if (arg1 == 1000) {
//            myWebView.loadUrl("javascript:myFunction()");
//            v4_webview.loadUrl(url + getURLToken());
            try {

//                v4_webview.loadUrl("javascript:goInSuccess('" + amount + "','" + time1 + "','" + time3 + "')");
//                v4_webview.loadUrl(jsonObject);
                v4_webview.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        v4_webview.clearHistory();
                    }
                }, 1000);
            } catch (Exception e) {
            }
        } else if (arg1 == 2000) {

            v4_webview.clearHistory();

//            v4_webview.loadUrl("javascript:goOutSuccess('" + amount1 + "','" + time2 + "')");
            v4_webview.postDelayed(new Runnable() {
                @Override
                public void run() {
                }
            }, 1000);
        }


    }

    public class JsInterfaces {
        private Context mContext;


        public JsInterfaces(Context mContext) {
            super();
            this.mContext = mContext;

        }



        // 在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
        @JavascriptInterface
        public void pleaseLogin(String url) {


        }


        @JavascriptInterface
        public void finishActivity() {

            V6WebviewChildActivity.this.finish();
        }


    }



    @JavascriptInterface
    public void setactivity(String activity) {

        Log.e("activity", activity);

        Intent intent;
        try {
            intent = new Intent(V6WebviewChildActivity.this,
                    Class.forName(activity));
            startActivity(intent);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    @Override
    protected void onRestart() {
        super.onRestart();

    }


    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.e("进度", newProgress + "");
            if (newProgress == 100) {
              dismissLoading();
            } else {
             showLoading();

            }
            super.onProgressChanged(view, newProgress);

        }


        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.e("console", "[" + consoleMessage.messageLevel() + "] " + consoleMessage.message() + "(" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + ")");
            return super.onConsoleMessage(consoleMessage);
        }
    };


    private void initView() {

    }


}
